import { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Package, Calendar, DollarSign, CheckCircle, Clock, XCircle, Eye, ChevronLeft, ChevronRight, ArrowLeft as BackArrow, CreditCard, Ban } from 'lucide-react';
import { useLanguage } from '@kernelproxy/i18n';
import { orderService } from '../../services/order';
import { Order } from '../../types/order';
import { StripePaymentModal } from '../../components/StripePaymentModal';
import { useToast } from '../../contexts/ToastContext';

const ITEMS_PER_PAGE = 10;

const Orders = () => {
  const { language } = useLanguage();
  const navigate = useNavigate();
  const toast = useToast();
  const [searchParams] = useSearchParams();
  const [orders, setOrders] = useState<Order[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [showStripePayment, setShowStripePayment] = useState(false);
  const [showCancelConfirm, setShowCancelConfirm] = useState(false);
  const [isCancelling, setIsCancelling] = useState(false);

  const getLink = (path: string) => {
    return language === 'zh-CN' ? `/zh-CN${path}` : path;
  };

  // Fetch orders from backend
  useEffect(() => {
    const fetchOrders = async () => {
      setIsLoading(true);
      try {
        // Get orders from localStorage (will be replaced with API call later)
        const fetchedOrders = orderService.getOrders();
        setOrders(fetchedOrders);

        // Check if there's an order ID in query params
        const orderId = searchParams.get('id');
        if (orderId) {
          const order = fetchedOrders.find(o => o.id === orderId);
          if (order) {
            setSelectedOrder(order);
          }
        }
      } catch (error) {
        console.error('Error fetching orders:', error);
        toast.error(language === 'zh-CN' ? '加载订单失败' : 'Failed to load orders');
      } finally {
        setIsLoading(false);
      }
    };

    fetchOrders();
  }, [language, searchParams, toast]);

  // Handle checkout - open Stripe payment modal
  const handleCheckout = (order: Order) => {
    setSelectedOrder(order);
    setShowStripePayment(true);
  };

  // Handle successful payment
  const handlePaymentSuccess = async () => {
    if (!selectedOrder) return;

    try {
      const success = await orderService.updateOrderPayment(selectedOrder.id, 'Stripe');
      if (success) {
        toast.success(language === 'zh-CN' ? '支付成功！' : 'Payment successful!');
        setShowStripePayment(false);
        // Refresh orders
        const updatedOrders = orderService.getOrders();
        setOrders(updatedOrders);
        const updatedOrder = updatedOrders.find(o => o.id === selectedOrder.id);
        if (updatedOrder) {
          setSelectedOrder(updatedOrder);
        }
      } else {
        toast.error(language === 'zh-CN' ? '更新订单状态失败' : 'Failed to update order status');
      }
    } catch (error) {
      console.error('Error updating order:', error);
      toast.error(language === 'zh-CN' ? '支付处理失败' : 'Payment processing failed');
    }
  };

  // Handle cancel order
  const handleCancelOrder = async () => {
    if (!selectedOrder) return;

    setIsCancelling(true);
    try {
      const result = await orderService.cancelOrder(selectedOrder.id);
      if (result.success) {
        toast.success(language === 'zh-CN' ? '订单已取消' : 'Order cancelled successfully');
        setShowCancelConfirm(false);
        // Refresh orders
        const updatedOrders = orderService.getOrders();
        setOrders(updatedOrders);
        const updatedOrder = updatedOrders.find(o => o.id === selectedOrder.id);
        if (updatedOrder) {
          setSelectedOrder(updatedOrder);
        }
      } else {
        toast.error(result.error || (language === 'zh-CN' ? '取消订单失败' : 'Failed to cancel order'));
      }
    } catch (error) {
      console.error('Error cancelling order:', error);
      toast.error(language === 'zh-CN' ? '取消订单失败' : 'Failed to cancel order');
    } finally {
      setIsCancelling(false);
    }
  };

  const getStatusBadge = (status: Order['status']) => {
    const badges = {
      completed: {
        icon: CheckCircle,
        text: language === 'zh-CN' ? '已完成' : 'Completed',
        className: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
      },
      pending: {
        icon: Clock,
        text: language === 'zh-CN' ? '处理中' : 'Pending',
        className: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
      },
      failed: {
        icon: XCircle,
        text: language === 'zh-CN' ? '失败' : 'Failed',
        className: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
      },
      refunded: {
        icon: DollarSign,
        text: language === 'zh-CN' ? '已退款' : 'Refunded',
        className: 'bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-400',
      },
    };

    const badge = badges[status];
    const Icon = badge.icon;

    return (
      <span className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-sm font-medium ${badge.className}`}>
        <Icon size={16} />
        {badge.text}
      </span>
    );
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString(language === 'zh-CN' ? 'zh-CN' : 'en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const totalPages = Math.ceil(orders.length / ITEMS_PER_PAGE);
  const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
  const endIndex = startIndex + ITEMS_PER_PAGE;
  const currentOrders = orders.slice(startIndex, endIndex);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  if (selectedOrder) {
    return (
      <div className="space-y-6">
        <div>
          <button
            onClick={() => setSelectedOrder(null)}
            className="flex items-center text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 mb-2 transition-colors"
          >
            <BackArrow size={20} className="mr-2" />
            {language === 'zh-CN' ? '返回订单列表' : 'Back to Orders'}
          </button>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
            {language === 'zh-CN' ? '订单详情' : 'Order Details'}
          </h1>
        </div>

        <div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
          <div className="flex justify-between items-start mb-6">
            <div>
              <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
                {selectedOrder.orderNumber}
              </h2>
              <div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400">
                <Calendar size={16} />
                {formatDate(selectedOrder.date)}
              </div>
            </div>
            {getStatusBadge(selectedOrder.status)}
          </div>

          <div className="border-t border-gray-200 dark:border-gray-700 pt-6 mb-6">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              {language === 'zh-CN' ? '订单项目' : 'Order Items'}
            </h3>
            <div className="space-y-4">
              {selectedOrder.items.map((item) => (
                <div
                  key={item.id}
                  className="flex justify-between items-start p-4 bg-gray-50 dark:bg-gray-900 rounded-lg"
                >
                  <div className="flex-1">
                    <h4 className="font-semibold text-gray-900 dark:text-white mb-2">
                      {item.productName}
                    </h4>
                    <div className="space-y-1 text-sm text-gray-600 dark:text-gray-400">
                      {item.traffic && (
                        <div>{language === 'zh-CN' ? '流量：' : 'Traffic: '}{item.traffic} GB</div>
                      )}
                      {item.ips && (
                        <div>{language === 'zh-CN' ? 'IP 数量：' : 'IPs: '}{item.ips}</div>
                      )}
                      {item.period && (
                        <div>{language === 'zh-CN' ? '周期：' : 'Period: '}{item.period}</div>
                      )}
                      <div>{language === 'zh-CN' ? '数量：' : 'Quantity: '}{item.quantity}</div>
                    </div>
                  </div>
                  <div className="text-right">
                    <div className="font-semibold text-gray-900 dark:text-white">
                      ${(item.price || 0).toFixed(2)}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="border-t border-gray-200 dark:border-gray-700 pt-6">
            <div className="space-y-4 mb-6">
              {selectedOrder.paymentMethod && (
                <div className="flex justify-between items-center">
                  <span className="text-gray-600 dark:text-gray-400">
                    {language === 'zh-CN' ? '支付方式' : 'Payment Method'}:
                  </span>
                  <span className="font-medium text-gray-900 dark:text-white">
                    {selectedOrder.paymentMethod}
                  </span>
                </div>
              )}
              <div className="flex justify-between items-center">
                <span className="text-gray-600 dark:text-gray-400">
                  {language === 'zh-CN' ? '支付状态' : 'Payment Status'}:
                </span>
                <span className={`font-medium ${
                  selectedOrder.paymentStatus === 'paid' 
                    ? 'text-green-600 dark:text-green-400' 
                    : selectedOrder.paymentStatus === 'unpaid'
                    ? 'text-yellow-600 dark:text-yellow-400'
                    : 'text-red-600 dark:text-red-400'
                }`}>
                  {selectedOrder.paymentStatus === 'paid' 
                    ? (language === 'zh-CN' ? '已支付' : 'Paid')
                    : selectedOrder.paymentStatus === 'unpaid'
                    ? (language === 'zh-CN' ? '未支付' : 'Unpaid')
                    : (language === 'zh-CN' ? '已退款' : 'Refunded')}
                </span>
              </div>
            </div>
            
            <div className="flex justify-between items-center text-xl font-bold pt-4 border-t border-gray-200 dark:border-gray-700">
              <span className="text-gray-900 dark:text-white">
                {language === 'zh-CN' ? '总计' : 'Total'}:
              </span>
              <span className="text-blue-600 dark:text-blue-400">
                ${(selectedOrder.total || 0).toFixed(2)}
              </span>
            </div>

            {/* Action buttons */}
            <div className="flex gap-3 mt-6">
              {/* Checkout button for unpaid orders */}
              {selectedOrder.paymentStatus === 'unpaid' && (
                <button
                  onClick={() => setShowStripePayment(true)}
                  className="flex-1 px-6 py-3 bg-gradient-to-r from-[#00d4ff] to-[#0f1c3f] text-white rounded-lg font-semibold transition-all flex items-center justify-center gap-2 shadow-lg hover:opacity-90"
                >
                  <CreditCard size={20} />
                  {language === 'zh-CN' ? '立即支付' : 'Checkout'}
                </button>
              )}

              {/* Cancel button for pending/unpaid orders */}
              {(selectedOrder.status === 'pending' || selectedOrder.paymentStatus === 'unpaid') && 
               selectedOrder.status !== 'completed' && 
               selectedOrder.status !== 'refunded' && (
                <button
                  onClick={() => setShowCancelConfirm(true)}
                  className="flex-1 px-6 py-3 border-2 border-red-500 text-red-500 rounded-lg font-semibold transition-all flex items-center justify-center gap-2 hover:bg-red-50 dark:hover:bg-red-900/20"
                >
                  <Ban size={20} />
                  {language === 'zh-CN' ? '取消订单' : 'Cancel Order'}
                </button>
              )}
            </div>
          </div>
        </div>

        {/* Cancel Confirmation Modal */}
        {showCancelConfirm && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6">
              <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-4">
                {language === 'zh-CN' ? '确认取消订单' : 'Confirm Cancel Order'}
              </h3>
              <p className="text-gray-600 dark:text-gray-400 mb-6">
                {language === 'zh-CN' 
                  ? `您确定要取消订单 ${selectedOrder.orderNumber} 吗？此操作无法撤销。`
                  : `Are you sure you want to cancel order ${selectedOrder.orderNumber}? This action cannot be undone.`}
              </p>
              <div className="flex gap-3">
                <button
                  onClick={() => setShowCancelConfirm(false)}
                  disabled={isCancelling}
                  className="flex-1 px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50"
                >
                  {language === 'zh-CN' ? '返回' : 'Go Back'}
                </button>
                <button
                  onClick={handleCancelOrder}
                  disabled={isCancelling}
                  className="flex-1 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isCancelling 
                    ? (language === 'zh-CN' ? '取消中...' : 'Cancelling...') 
                    : (language === 'zh-CN' ? '确认取消' : 'Confirm Cancel')}
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Stripe Payment Modal */}
        <StripePaymentModal
          isOpen={showStripePayment}
          amount={selectedOrder.total}
          onSuccess={handlePaymentSuccess}
          onClose={() => setShowStripePayment(false)}
        />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div>
        <button
          onClick={() => navigate(getLink('/dashboard'))}
          className="flex items-center text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 mb-2 transition-colors"
        >
          <BackArrow size={20} className="mr-2" />
          {language === 'zh-CN' ? '返回概览' : 'Back to Overview'}
        </button>
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
          {language === 'zh-CN' ? '我的订单' : 'My Orders'}
        </h1>
      </div>

      {orders.length === 0 ? (
        <div className="bg-white dark:bg-gray-800 rounded-xl p-12 text-center shadow-lg">
          <div className="inline-flex items-center justify-center w-24 h-24 bg-gray-100 dark:bg-gray-700 rounded-full mb-6">
            <Package className="text-gray-400 dark:text-gray-500" size={48} />
          </div>
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">
            {language === 'zh-CN' ? '暂无订单' : 'No orders yet'}
          </h2>
          <p className="text-gray-600 dark:text-gray-300 mb-8">
            {language === 'zh-CN'
              ? '您还没有任何订单。开始购物以查看订单历史。'
              : "You haven't placed any orders yet. Start shopping to see your order history."}
          </p>
          <button
            onClick={() => navigate(getLink('/dashboard'))}
            className="bg-gradient-to-r from-blue-600 to-purple-600 text-white py-3 px-8 rounded-lg hover:from-blue-700 hover:to-purple-700 transition-all duration-300 font-semibold"
          >
            {language === 'zh-CN' ? '开始购物' : 'Start Shopping'}
          </button>
        </div>
      ) : (
        <div className="space-y-4">
          {currentOrders.map((order) => (
            <div
              key={order.id}
              className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-md border border-gray-200 dark:border-gray-700 hover:shadow-lg transition-shadow"
            >
              <div className="flex justify-between items-start mb-4">
                <div className="flex-1">
                  <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-2">
                    {order.orderNumber}
                  </h3>
                  <div className="flex items-center gap-4 text-sm text-gray-600 dark:text-gray-400">
                    <div className="flex items-center gap-1">
                      <Calendar size={16} />
                      {formatDate(order.date)}
                    </div>
                    <div className="flex items-center gap-1">
                      <Package size={16} />
                      {order.items.length} {language === 'zh-CN' ? '件商品' : 'items'}
                    </div>
                  </div>
                </div>
                <div className="text-right">
                  {getStatusBadge(order.status)}
                  <div className="mt-2 text-xl font-bold text-gray-900 dark:text-white">
                    ${(order.total || 0).toFixed(2)}
                  </div>
                </div>
              </div>

              <div className="flex gap-3">
                <button
                  onClick={() => setSelectedOrder(order)}
                  className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
                >
                  <Eye size={18} />
                  {language === 'zh-CN' ? '查看详情' : 'View Details'}
                </button>
                {order.status === 'completed' && (
                  <button
                    onClick={() => {
                      // TODO: Implement reorder functionality
                      alert(language === 'zh-CN' ? '重新下单功能开发中' : 'Reorder feature coming soon');
                    }}
                    className="px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
                  >
                    {language === 'zh-CN' ? '重新下单' : 'Reorder'}
                  </button>
                )}
              </div>
            </div>
          ))}

          {totalPages > 1 && (
            <div className="flex justify-between items-center mt-6">
              <div className="text-sm text-gray-600 dark:text-gray-400">
                {language === 'zh-CN' ? '显示' : 'Showing'} {startIndex + 1}-{Math.min(endIndex, orders.length)} {language === 'zh-CN' ? '共' : 'of'} {orders.length}
              </div>
              <div className="flex gap-2">
                <button
                  onClick={() => setCurrentPage(currentPage - 1)}
                  disabled={currentPage === 1}
                  className="flex items-center gap-2 px-4 py-2 rounded-lg bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  <ChevronLeft size={18} />
                  <span>{language === 'zh-CN' ? '上一页' : 'Previous'}</span>
                </button>
                <button
                  onClick={() => setCurrentPage(currentPage + 1)}
                  disabled={currentPage === totalPages}
                  className="flex items-center gap-2 px-4 py-2 rounded-lg bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  <span>{language === 'zh-CN' ? '下一页' : 'Next'}</span>
                  <ChevronRight size={18} />
                </button>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default Orders;
